import CryptoJS from "crypto-js";

const XF_TTS = {
  appId: "ff787ecb",
  apiKey: "69196fd168836c0caccc791dbd4c48a1",
  apiSecret: "NTk1MjZhMDcwZmI1MTE0YmY5NmJhZWFm",
  hostUrl: "wss://tts-api.xfyun.cn/v2/tts", // 科大讯飞 WebSocket 地址

  getAuthUrl() {
    let date = new Date().toGMTString();
	console.log('date', date)
    let signatureOrigin = `host: tts-api.xfyun.cn\ndate: ${date}\nGET /v2/tts HTTP/1.1`;
    let signatureSha = CryptoJS.HmacSHA256(signatureOrigin, this.apiSecret);
    let signature = CryptoJS.enc.Base64.stringify(signatureSha);
    let authorizationOrigin = `api_key="${this.apiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`;
    let authorization = btoa(authorizationOrigin);
    return `${this.hostUrl}?authorization=${authorization}&date=${encodeURIComponent(date)}&host=tts-api.xfyun.cn`;
  },

  async textToSpeech(text, onAudioReady) {
    let ws = new WebSocket(this.getAuthUrl());

    ws.onopen = () => {
      let params = {
        common: { app_id: this.appId },
        business: {
          aue: "lame", // MP3 格式
          auf: "audio/L16;rate=16000",
          vcn: "xiaoyan", // 选择超拟人发音人
          speed: 50,
          volume: 50,
          pitch: 50,
          bgs: 0,
        },
        data: {
          text: btoa(unescape(encodeURIComponent(text))), // Base64 编码
          status: 2,
        },
      };
      ws.send(JSON.stringify(params));
    };

    let audioChunks = [];

    ws.onmessage = (event) => {
      let response = JSON.parse(event.data);
      if (response.data && response.data.audio) {
        let audioData = atob(response.data.audio);
        audioChunks.push(audioData);
      }
      if (response.code !== 0) {
        console.error("TTS 错误:", response);
        ws.close();
      }
    };

    ws.onerror = (err) => console.error("WebSocket 错误:", err);
    
    ws.onclose = () => {
      let blob = new Blob(audioChunks, { type: "audio/mp3" });
      let audioUrl = URL.createObjectURL(blob);
      onAudioReady(audioUrl);
    };
  },
};

export default XF_TTS;